import React, { PureComponent } from "react";

import PrizeGridBox from "./prize/PrizeGrid";
import MyPrize from "./prize/components/MyPrize";
import PrizeRule from "./prize/components/PrizeRule";
import ScrollWinner from "./prize/components/ScrollWinner";

import { PrizeWrapper } from "./style.js";

import { getUrlParamByName } from "@Utils";
import { baseURL } from "@Services";
import Login from "@Components/Login/Login";
import { isMiniProgram } from "@Utils";

import { getVipPowerConfigInfoApi, getMobiNum } from "@Services/api";

import ContextApp from "./context.js";

export default class index extends PureComponent {
  constructor(props) {
    super(props);
    // 获取openid
    const search = window.location.search;
    this.loginRef = React.createRef();
    this.scrollWinneref = React.createRef();

    this.state = {
      openId: getUrlParamByName("openId", search),
      mobile: Number(getUrlParamByName("phone", search)) || "",
      activeId: getUrlParamByName("id", search), // 活动id
      clientType: getUrlParamByName("clientType", search), // 设备
      deviceCode: getUrlParamByName("deviceCode", search), // 设备
      from: getUrlParamByName("from", search), // ? 没用
      sonumber: getUrlParamByName("sonumber", search), // 单号
      weixin: getUrlParamByName("weixin", search), // 来自的页面WX
      fromH5Url: getUrlParamByName("fromh5url", search), // 来自的页面H5
      isShow_MyPrize: false,
      isShowLogin: false,

      handleShowLogin: this.handleShowLogin.bind(this), // 登录组件显示隐藏
      freshData: this.freshData.bind(this), // 抽奖接口
      handleShowMyPrize: this.handleShowMyPrize.bind(this), // 开关我的奖品

      prizeDatalist: [0, 1, 2, 3, 4, 5, 6, 7], // 奖品列表
      surplus: undefined, // 抽奖次数
      surplusType: undefined,
      skins: {
        top_img: "",
      },
    };
  }

  componentDidMount() {
    if (!isMiniProgram()) {
      // debugger
      window.history.pushState(null, null, document.URL);
      window.addEventListener("popstate", this.navigateBackEvent.bind(this));
    }
    this.freshData();
  }

  freshData() {
    this.getVipPowerConfigInfoApi();
    this.scrollWinneref.current.init();
    this.getMobiNum();
  }

  async getMobiNum() {
    let { code = null, data = null } = await getMobiNum({
      phone: this.state.mobile,
      oid: 108,
    });

    if (code == 200) {
      this.setState({ mobiNum: data });
    }
  }

  // 奖品接口
  async getVipPowerConfigInfoApi() {
    let { code = null, data = null } = await getVipPowerConfigInfoApi({
      id: this.state.activeId,
      phone: this.state.mobile,
    });

    //1 number 次数
    //2 numberDaySurplus	每天剩余

    if (code == 200 && data) {
      let surplus = getSurplus(data); // 剩余次数

      data.infoList.map((v, i) => {
        v.index = i;
      });
      // 计算剩余次数

      function getSurplus(data) {
        var Surplus = undefined;
        // 无限 -1
        if (data.type == 0) Surplus = -1;
        else {
          Surplus = data.numberSurplus;
        }
        return Surplus;
      }

      // 获取皮肤
      const getSkinTemplate = () => {
        let data = {
          templateInfo: {
            top_img: {
              detailType: 1,
              detail:
                "https://xy.cozzia.com.cn/chair/image/ioReadImage?imgPath=/ogawa/file/upload/advertising_position/202204/1648795015083.jpg",
            },
            mid_title: {
              detailType: 2,
              detail: "#FFE262",
            },
            mid_outBg: {
              detailType: 2,
              detail: "#327BF6",
            },
            mid_innerBg: {
              detailType: 2,
              detail: "#86E9FB",
            },
            mid_prizeBtn: {
              detailType: 2,
              detail: "linear-gradient(0deg, #FD520F, #FDA22D);",
            },
            mid_mobi: {
              detailType: 2,
              detail: "#FFFFFF",
            },
            mid_myPrizeBg: {
              detailType: 2,
              detail: "#FFFFFF",
            },
            mid_myPrizeFontColor: {
              detailType: 2,
              detail: "black",
            },
          },
        };

        let {
            top_img,
            mid_title,
            mid_outBg,
            mid_innerBg,
            mid_prizeBtn,
            mid_mobi,
            mid_myPrizeBg,
            mid_myPrizeFontColor,
          } = data.templateInfo,
          skins = {};

        skins.top_img = getBackgroundByType(top_img);
        skins.mid_title = getColorByType(mid_title);
        skins.mid_outBg = getBackgroundByType(mid_outBg);
        skins.mid_innerBg = getBackgroundByType(mid_innerBg);
        skins.mid_prizeBtn = getBackgroundByType(mid_prizeBtn);
        skins.mid_mobi = getColorByType(mid_mobi);
        skins.mid_myPrizeBg = getBackgroundByType(mid_myPrizeBg);
        skins.mid_myPrizeFontColor = getColorByType(mid_myPrizeFontColor);

        // 渲染背景色
        this.getImgColor(top_img.detail);

        this.setState({ skins });
      };

      const getBackgroundByType = (data) => {
        if (data.detailType == 1) {
          // detailType1=图片
          return `background-image:url(${data.detail});
          background-repeat: no-repeat;
          `;
          // 渲染底色
        } else if (data.detailType == 2) {
          return `background:${data.detail}`;
        }
      };

      const getColorByType = (data) => {
        return `color:${data.detail}`;
      };

      getSkinTemplate(data.template);

      this.setState({
        prizeDatalist: data.infoList,
        midTitle: data.name,
        surplus,
        surplusType: data.type,
      });
    }
  }

  // 若有登录则返回时携带参数
  navigateBackEvent() {
    var baseUrl = `${baseURL}/cloudH5/#/`;
    window.history.pushState(null, null, document.URL);
    window.location.href = `${baseUrl}index?deviceCode=${this.state.deviceCode}&code=${this.state.openId}&payMode=${this.state.clientType}&from=reactPrize&mobile=${this.state.mobile}&sonumber=${this.state.sonumber}&weixin=${this.state.weixin}&fromh5url=${this.state.fromH5Url}`;
  }

  // 显示隐藏
  handleShowMyPrize(param = true) {
    if (!this.state.mobile) return this.handleShowLogin(true);
    this.setState({ isShow_MyPrize: param });
  }

  // 显示隐藏登录框
  handleShowLogin(isShowLogin = true) {
    this.setState({ isShowLogin }, () => {
      //获取验证码前所需的盐巴
      if (isShowLogin) this.loginRef.current.getSmsCCC();
    });
  }

  render() {
    return (
      <ContextApp.Provider value={this.state}>
        <PrizeWrapper top_img={this.state.skins.top_img}>
          <div className="Prize">
            {/* 头部banner */}
            <div className="prize_topbg">
              <ScrollWinner ref={this.scrollWinneref} />
            </div>

            {/* 转盘 */}
            <PrizeGridBox />

            {/* 规则 */}
            <PrizeRule />
            {/* 我的奖品页 */}
            <MyPrize />
            {/* 登录页 */}
            <Login
              ref={this.loginRef}
              closeLogin={() => {
                this.handleShowLogin(false);
              }}
            />
          </div>

          {/* 吸色画布 */}
          <canvas id="canvas" style={{ display: "none" }}></canvas>
        </PrizeWrapper>
      </ContextApp.Provider>
    );
  }

  // 吸图片颜色算法
  getImgColor(imgSrc) {
    let img = new Image();
    let canvas = document.getElementById("canvas");
    let ctx = canvas.getContext("2d");
    var topImgBottomColor;

    img.src = imgSrc;
    img.crossOrigin = "anonymous";

    img.onload = () => {
      const { height: iH, width: iW } = img;
      ctx.drawImage(img, 0, iH - 5, iW, 5, 0, 0, iW, 5);
      // (img, sx, sy, sw, sh, dx, dy, dw, dh)
      canvas.style.display = "none";
      let imgData = ctx.getImageData(0, 0, img.width, img.height).data;
      var red = imgData[0];
      var green = imgData[1];
      var blue = imgData[2];
      var alpha = imgData[3];

      topImgBottomColor = `rgba(${red},${green},${blue},${alpha})`;

      document.getElementsByClassName("Prize")[0].style.backgroundColor =
        topImgBottomColor;
    };
  }
}
